//
//  OYPickerCollectionView.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/10.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
let OYPickerCollectionViewCellIdentifier = "OYPickerCollectionViewCellIdentifier"
class OYPickerCollectionView: UICollectionView {

     // MARK: -控件懒加载
    lazy var imageList:[UIImage] = [UIImage ]()
    
    let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    var closure:( ()-> ())?
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let itemMargin:CGFloat = 8
        let itemWidth:CGFloat = (ScreenWidth - 20 - 2 * itemMargin) / 3
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
    
        setupUI()
    }
    
     // MARK: -添加、布局子控件
    func setupUI()  {
        
         // MARK: -设置背景颜色
        backgroundColor = UIColor.brown
        dataSource = self
        delegate = self
         // MARK: -注册cell
        register(OYPickerCollectionViewCell.self, forCellWithReuseIdentifier: OYPickerCollectionViewCellIdentifier)
        
        // 默认隐藏
        isHidden = true
    }
    
     // MARK: -将Vc中压缩后的图片添加至CollectionView的图片数组中
    func addImage(image:UIImage)  {
        
        if imageList.count >= 9 {
            return
        }
        // 如果有图片，显示本CollectionView
        isHidden = false
        
        imageList.append(image)
         // MARK: -添加图片的时候刷新CollectionView
        reloadData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension OYPickerCollectionView:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if imageList.count == 0 || imageList.count == 9 {
            return imageList.count
        }else {
        
            return imageList.count + 1
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OYPickerCollectionViewCellIdentifier, for: indexPath) as! OYPickerCollectionViewCell
        
        if indexPath.item == imageList.count {
            cell.image = nil
        }else {
            
            cell.image = imageList[indexPath.item]
            cell.indexPath = indexPath
            
            // 执行cell中删除button的
            cell.deleteBtnClosure = { [weak self] (index) -> Void in
                self?.imageList.remove(at: index)
                
                // 如果没有图片，则隐藏CollectionView
                if self?.imageList.count == 0 {
                    self?.isHidden = true
                }
                
                self?.reloadData()
            }
        }
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == imageList.count {
            // 如果是最后一个按钮，执行闭包
            closure?()
        }
    }
    
}

class OYPickerCollectionViewCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    // 删除button的回调闭包
    var deleteBtnClosure: ((Int)->())?
    // 当前cel的IndexPath
    var indexPath:IndexPath?
    
     // MARK: -控件懒加载
    lazy var imageView:UIImageView = {
        let imageView = UIImageView()
        
        return imageView
    }()
    
    var image:UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                deleteButton.isHidden = true
            }else {
                imageView.image = image
                deleteButton.isHidden = false
            }
        }
    }
    
    lazy var deleteButton:UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        button.sizeToFit()
        
        button.addTarget(self, action: #selector(deleteImage), for: .touchUpInside)
        
        
        return button
    }()

    
     // MARK: -删除添加的图片
    func deleteImage() {
        // 获取当前cell的index
        if let index = indexPath{
            // 通过闭包进行回调
            deleteBtnClosure?(index.item)
        }
    }
    
    func setupUI() {
        addSubview(imageView)
        addSubview(deleteButton)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        deleteButton.snp_makeConstraints { (make) in
            make.right.equalTo(self)
            make.top.equalTo(self)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
